import * as types from '../_types/transaction';

interface CoinInfo{
    coinType: string,
    amount: string | number,
    locked: string | number,
    avaliable: string | number
}

const initialState: Array<CoinInfo> = [
    {
        coinType: '1',
        amount: 0,
        locked: 0,
        avaliable: 0
    }
]

const _getIndex = (arr:Array<CoinInfo>, coinType: string) => {
    let index = arr.findIndex(v => v.coinType === coinType);
    if (index < 0) {
        return null;
    }
    return index;
}

export default function transaction(state: Array<CoinInfo> = initialState, action) {
    const {type, paylaod} = action;
    switch(type) {
        case types.Buy: {
            let {targetCoinType, targetAmount, payCoinType, payAmount} = paylaod;
            let index = _getIndex(state, targetCoinType);
            if (index === null) {
                return {
                    ...state
                }
            }
            state[index].locked += targetAmount;
            state[index].avaliable = Number(state[index].avaliable) - Number(targetAmount);
            return {
                ...state
            }
        }
        case types.Sell: {
            let {targetCoinType, targetAmount, payCoinType, payAmount} = paylaod;
            let index = _getIndex(state, targetCoinType);
            if(index === null) {
                return {
                    ...state
                }
            }
            state[index].locked += targetAmount;
            state[index].avaliable -= targetAmount;
            return {
                ...state
            }
        }
        case types.Deposit: {
            let {coinType, amount} = action;
            let index = _getIndex(state, coinType);
            if (index === null) {
                return {
                    ...state
                }
            }
        }
        case types.Withdraw: {
            let {coinType, amount} = action;
            let index = _getIndex(state, coinType);
            if (index === null) {
                return {
                    ...state
                }
            }
        }
        default: {
            return state;
        }
    }
}